﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Telerik.Web.UI;

namespace Landscape.WebApp.Handlers
{
    /// <summary>
    /// Summary description for OmniAsyncFileUploader
    /// </summary>
    public class LanscapeAsyncFileUploader : AsyncUploadHandler
    {

        protected override IAsyncUploadResult Process(UploadedFile file, HttpContext context, IAsyncUploadConfiguration configuration, string tempFileName)
        {
            var baseProcess = base.Process(file, context, configuration, tempFileName);

            //string source = string.Format(@"{0}\TempFiles\{1}", HttpContext.Current.Server.MapPath("").Replace("Handlers", string.Empty), tempFileName);
            //string destination = string.Format(@"{0}\Files\{1}", HttpContext.Current.Server.MapPath("").Replace("Handlers", string.Empty), file.FileName);

            string sFile = (Directory.Exists(configuration.TempTargetFolder) ? configuration.TempTargetFolder : HttpContext.Current.Server.MapPath(configuration.TempTargetFolder));
            string tFile = (Directory.Exists(configuration.TargetFolder) ? configuration.TempTargetFolder : HttpContext.Current.Server.MapPath(configuration.TargetFolder));

            string fName = (file.FileName.Contains('\\') ? file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1) : file.FileName);
            string source = string.Format(@"{0}\{1}", sFile, tempFileName);
            string destination = string.Format(@"{0}\{1}", tFile, fName);

            if (File.Exists(destination))
            {
                File.Delete(destination);
            }

            if (File.Exists(source))
            {
                File.Copy(source, destination);
            }

            return baseProcess;
        }
    }
}